package org.rpn4j.scan;

import java.util.ArrayList;
import java.util.List;

import org.rpn4j.core.Function;
import org.rpn4j.core.Operand;
import org.rpn4j.core.Value;
import org.rpn4j.core.Variable;
import org.rpn4j.ctx.Context;

/**
 * The StringScanner is a simple {@link Scanner} implementation which takes an rpn expression as string.
 * 
 * @author hillger.t
 */
public class StringScanner implements Scanner {
  private Context context;
  private String expression;

  public StringScanner() {}

  public StringScanner(String expression) {
    this.expression = expression;
  }

  public void setExpression(String expression) {
    this.expression = expression;
  }

  @Override
  public void setContext(Context context) {
    this.context = context;
  }

  public List<Operand> get() {
    List<Operand> res = new ArrayList<Operand>();

    for (String item : expression.split(" ")) {

      switch (context.getType(item)) {
        case FUNCTION:
          Function function = context.findFunction(item);
          res.add(function);
          break;
        case VARIABLE:
          Variable variable = context.findVariable(item);
          res.add(variable);
          break;
        default:
          double value = Double.valueOf(item);
          res.add(Value.newInstance(value));
      }
    }

    return res;
  }
}
